﻿using IdentityServer4.Models;
using IdentityServer4.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace User.Identity.Services
{
    public class ProfileService
        : IProfileService
    {
        public Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var subject = context.Subject ?? throw new ArgumentNullException("subject is null");

            var subjectId = subject.Claims.Where(c => c.Type == "sub").FirstOrDefault().Value;
            if (!int.TryParse(subjectId, out int iSubjectId))
            {
                throw new ArgumentNullException("sub id is null");
            }

            context.IssuedClaims = subject.Claims.ToList();
            return Task.CompletedTask;
        }

        public Task IsActiveAsync(IsActiveContext context)
        {
            var subject = context.Subject ?? throw new ArgumentNullException("subject is null");

            var subjectId = subject.Claims.Where(c => c.Type == "sub").FirstOrDefault().Value;
            context.IsActive = int.TryParse(subjectId, out int iSubjectId);
            return Task.CompletedTask;
        }
    }
}
